package jgo.plugins.auth;

import java.util.function.Function;

import jgo.Context;
import jgo.Handler;
import jgo.JGo;
import jgo.User;
import jgo.core.MiddlewarePlugin;
import jgo.plugins.server.HttpContext;

public class AuthenticationMiddleware extends MiddlewarePlugin {
	private Function<Context, User> authenticationStrategy;

	public AuthenticationMiddleware(Function<Context, User> authenticationStrategy) {
		this.authenticationStrategy = authenticationStrategy;
	}

	@Override
	public void handle(Context ctx, Handler next) {
		try {
			User user = authenticationStrategy.apply(ctx);
			if (user != null) {
				((HttpContext) ctx).user = (user);
				next.handle(ctx);
			} else {
				logger.warn("Authentication failed for request: {} {}", ctx.getMethod(), ctx.getPath());
				ctx.status(401).string("Unauthorized");
			}
		} catch (Exception e) {
			logger.error("Error during authentication", e);
			ctx.status(500).string("Internal Server Error");
		}
	}

	@Override
	public void init(JGo gin) {
		// 初始化逻辑，如果需要的话
		logger.info("AuthenticationMiddleware initialized");
	}

	@Override
	public String name() {
		return "Authentication";
	}

	// 提供一些预定义的认证策略
	public static Function<Context, User> bearerTokenStrategy(Function<String, User> tokenValidator) {
		return ctx -> {

			String authHeader = ((HttpContext) ctx).getHeader("Authorization");
			if (authHeader != null && authHeader.startsWith("Bearer ")) {
				String token = authHeader.substring(7);
				return tokenValidator.apply(token);
			}
			return null;
		};
	}

	public static Function<Context, User> basicAuthStrategy(
			Function<String, Function<String, User>> credentialsValidator) {
		return ctx -> {
			String authHeader = ((HttpContext) ctx).getHeader("Authorization");
			if (authHeader != null && authHeader.startsWith("Basic ")) {
				String encodedCredentials = authHeader.substring(6);
				String decodedCredentials = new String(java.util.Base64.getDecoder().decode(encodedCredentials));
				String[] parts = decodedCredentials.split(":", 2);
				if (parts.length == 2) {
					return credentialsValidator.apply(parts[0]).apply(parts[1]);
				}
			}
			return null;
		};
	}

	public static Function<Context, User> sessionStrategy(String sessionKey) {
		return ctx -> {
			String sessionId = ((HttpContext) ctx).getCookie(sessionKey);
			if (sessionId != null) {
				// 这里应该有实际的session验证逻辑
				// 这只是一个示例
				return new User(sessionId, "User-" + sessionId);
			}
			return null;
		};
	}
}